package com.ccteam.fluidmusic.ui.moment.imageview

import android.graphics.Bitmap
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.BitmapImageViewTarget
import com.ccteam.fluidmusic.databinding.FragmentImageViewBinding
import com.davemorrissey.labs.subscaleview.ImageSource
import com.luck.picture.lib.tools.MediaUtils
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author Xiaoc
 * @since 2021/4/7
 *
 * 图片大图查看详情内容Fragment
 */
@AndroidEntryPoint
class ImageViewFragment: Fragment() {

    private var _binding: FragmentImageViewBinding? = null
    private val binding get() = _binding!!

    private val imageViewViewModel by viewModels<ImageViewViewModel>()

    companion object{
        @JvmStatic
        fun newInstance(image: ImageViewData) =
            ImageViewFragment().apply {
                arguments = Bundle().apply {
                    putParcelable("image", image)
                }
            }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentImageViewBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        imageViewViewModel.image.observe(viewLifecycleOwner, {
            Glide.with(requireContext())
                .asBitmap()
                .load(it.imageUrl)
                .into(object: BitmapImageViewTarget(binding.photoView){
                    override fun setResource(resource: Bitmap?) {
                        if(resource == null){
                            return
                        }
                        val isLongImage = MediaUtils.isLongImg(resource.width,
                            resource.height
                        )
                        binding.progressLoading.hide()
                        binding.photoView.isVisible = !isLongImage
                        binding.subScaleImageView.isVisible = isLongImage
                        if(isLongImage){
                            binding.subScaleImageView.isQuickScaleEnabled = true
                            binding.subScaleImageView.isZoomEnabled = true
                            binding.subScaleImageView.setImage(ImageSource.bitmap(resource))
                        } else {
                            binding.photoView.setImageBitmap(resource)
                        }
                    }
                })
        })
    }

    override fun onDestroyView() {
        super.onDestroyView()

        _binding = null
    }
}